package com.xuesaieducation.zshddemo.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gensee.download.ErrorCode;
import com.gensee.download.VodDownLoader;
import com.gensee.entity.ChatMsg;
import com.gensee.entity.DocInfo;
import com.gensee.media.VODPlayer;
import com.gensee.utils.StringUtil;
import com.gensee.view.GSVideoView;
import com.xuesaieducation.zshddemo.R;
import com.xuesaieducation.zshddemo.ScreenUtils;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by ytf on 2018/1/15 015.
 * Description:
 */

public class VodFragment extends Fragment implements
        VODPlayer.OnVodPlayListener,
        SeekBar.OnSeekBarChangeListener,
        VodDownLoader.OnDownloadListener
{
    private static final int DURTIME = Toast.LENGTH_SHORT;

    Activity mContext;

    @BindView(R.id.layout)
    FrameLayout parent;
    @BindView(R.id.gsvideoview)
    GSVideoView mGSVideoView;
    @BindView(R.id.pause_resume)
    ImageView pauseResume;
    @BindView(R.id.progress)
    SeekBar progress;
    @BindView(R.id.left_time)
    TextView leftTime;
    @BindView(R.id.download)
    ImageView download;
    @BindView(R.id.full_screen)
    ImageView fullScreen;
    @BindView(R.id.controller)
    LinearLayout controller;

    Unbinder unbinder;
    VODPlayer mVodPlayer;

    //下载相关
    private VodDownLoader mVodDownLoader;
    private SharedPreferences preferences;

    Animation controllerAppearAnim, controllerDisappearAnim;

    public void setPlayer(VODPlayer player, Callback m)
    {
        this.mVodPlayer = player;
        callback = m;
    }

    public void setVideoViewVisible(boolean bVisible)
    {
        if (isAdded())
        {
            if (bVisible)
            {
                mGSVideoView.setVisibility(View.VISIBLE);
            } else
            {
                mGSVideoView.setVisibility(View.GONE);
            }
        }
    }


    Callback callback;
/**----------------------------------------------------------下载监听代码--------------------------------------------------------------*/
    @Override
    public void onDLFinish(String downLoadId, String localPath)
    {
        preferences.edit().putString(downLoadId, localPath).apply();
    }

    @Override
    public void onDLPrepare(String s)
    {

    }

    @Override
    public void onDLPosition(String s, int i)
    {

    }

    @Override
    public void onDLStart(String s)
    {
        myHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                Toast.makeText(mContext, "开始下载，退出页面将停止下载任务", DURTIME).show();
            }
        });
    }

    @Override
    public void onDLStop(String s)
    {

    }

    @Override
    public void onDLError(String s, int i)
    {

    }
    /**----------------------------------------------------------下载监听代码--------------------------------------------------------------*/
    public interface Callback
    {
        void isWait(boolean yn);
        void onStart();
        void onError(int code, String msg);
    }

    @Override
    public void onAttach(Context context)
    {
        super.onAttach(context);
        if (context instanceof Activity)
        {
            mContext = (Activity) context;
        }
        initAnim(context);
    }

    boolean isAnimGoing;
    boolean isOperateVisiable;

    private void initAnim(Context ctx)
    {
        controllerAppearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_bottom_top);
        controllerAppearAnim.setDuration(350);
        controllerDisappearAnim = AnimationUtils.loadAnimation(ctx, R.anim.anim_top_bottom);
        controllerDisappearAnim.setDuration(350);
        controllerAppearAnim.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
                isAnimGoing = true;
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                isAnimGoing = false;
                isOperateVisiable = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        controllerDisappearAnim.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {
                isAnimGoing = true;
            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                isAnimGoing = false;
                isOperateVisiable = false;
                controller.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
    }

    String vodId, localpath;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle bd = getArguments();
        if(bd != null)
        {
            vodId = bd.getString("play_param");
            localpath = bd.getString("play_path");
        }

        preferences = mContext.getSharedPreferences("gensee_config", Context.MODE_PRIVATE);
        if(!TextUtils.isEmpty(vodId))
        {
            lastPostion = preferences.getInt("last_position_" + vodId, 0);
        }
        //如果需要区分多用户，请使用带用户id的instance进行初始化，默认情况下用户id为0
        mVodDownLoader = VodDownLoader.instance(mContext, this, String.valueOf(mContext.getExternalFilesDir(null)));
        // 启动已存在且未完成的任务
        mVodDownLoader.download();
    }

    private String getVodIdOrLocalPath()
    {
        String vodIdOrLocalPath = null;
        if (!StringUtil.isEmpty(localpath))
        {
            vodIdOrLocalPath = localpath;
        } else if (!StringUtil.isEmpty(vodId))
        {
            vodIdOrLocalPath = vodId;
        }
        return vodIdOrLocalPath;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        return View.inflate(mContext, R.layout.frag_vod, null);
    }

    int parentPortraitWidth, parentPortraitHeight;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        parent.post(new Runnable()
        {
            @Override
            public void run()
            {
                parentPortraitWidth = parent.getMeasuredWidth();
                parentPortraitHeight = parent.getMeasuredHeight();
                fullScreen.setVisibility(View.VISIBLE);
            }
        });
        controller.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                controller.setVisibility(View.VISIBLE);
                controller.startAnimation(controllerAppearAnim);
            }
        }, 1500);
        initPlayer();
        progress.setOnSeekBarChangeListener(this);
    }

    private void initPlayer()
    {
        String vodIdOrLocalPath = getVodIdOrLocalPath();
        if (mVodPlayer != null)
        {
            mVodPlayer.setGSVideoView(mGSVideoView);
            mVodPlayer.play(vodIdOrLocalPath, this, "", false);
        }
    }

    @Override
    public void onDestroyView()
    {
        unbinder.unbind();
        myHandler.removeCallbacksAndMessages(null);
        myHandler = null;
        // 退出下载相关的功能时，释放掉
        if(mVodDownLoader != null)
        {
            mVodDownLoader.release();
            mVodDownLoader = null;
        }
        if(!TextUtils.isEmpty(vodId))
        {
            if(preferences != null)
                preferences.edit().putInt("last_position_" + vodId, lastPostion).apply();
        }
        super.onDestroyView();
    }

    @OnClick({R.id.layout, R.id.pause_resume,
            R.id.full_screen, R.id.download})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.layout:
                if (!isAnimGoing)
                {
                    if (isOperateVisiable)
                    {
                        controller.startAnimation(controllerDisappearAnim);
                    } else
                    {
                        controller.setVisibility(View.VISIBLE);
                        controller.startAnimation(controllerAppearAnim);
                    }
                }
                break;
            case R.id.pause_resume:
                if (VIEDOPAUSEPALY == 0)
                {
                    mVodPlayer.pause();
                } else if (VIEDOPAUSEPALY == 1)
                {
                    mVodPlayer.resume();
                }else if(VIEDOPAUSEPALY == 2)
                {
                    initPlayer();
                }
                break;
            case R.id.full_screen:
                if(ll != null)
                    ll.vodClick();
                break;
            case R.id.download:
                download(vodId);
                break;
        }
    }

    private void download(String vodId)
    {
        mVodDownLoader.setAutoDownloadNext(true);
        int ret = mVodDownLoader.download(vodId);
        switch (ret)
        {
            case ErrorCode.SUCCESS:
                Toast.makeText(mContext, "请稍后", DURTIME).show();
                download.setVisibility(View.GONE);
                break;
            case ErrorCode.DOWNLOADING_HAVE_EXIST:
                Toast.makeText(mContext, "当前已有下载任务 。目前的机制是单任务下载", DURTIME).show();
                break;
            case ErrorCode.DOWNLOADING_URL_NULL:
                Toast.makeText(mContext, "下载地址为空", DURTIME).show();
                break;
            case ErrorCode.OBJECT_HAVE_EXIST:
                Toast.makeText(mContext, "录制件已在下载队列中", DURTIME).show();
                break;
            case ErrorCode.OBJECT_IS_NULL:
                Toast.makeText(mContext, "传入参数为空", DURTIME).show();
                break;
            case ErrorCode.OBJECT_NOT_EXIST:
                Toast.makeText(mContext, "目标不存在", DURTIME).show();
                break;
            case ErrorCode.SDCARD_ERROR:
                Toast.makeText(mContext, "SD卡异常", DURTIME).show();
                break;
            default:
                break;
        }
    }

    /**----------------------------------------------------------播放器回调--------------------------------------------------------------*/
    @Override
    public void onInit(int result, boolean haveVideo, int duration, List<DocInfo> docInfos)
    {
        if (lastPostion >= duration - 1000)
        {
            lastPostion = 0;
        }
        Message message = new Message();
        message.what = MSG.MSG_ON_INIT;
        message.obj = docInfos;
        Bundle bundle = new Bundle();
        bundle.putInt(DURATION, duration);
        message.setData(bundle);
        myHandler.sendMessage(message);
    }

    @Override
    public void onPlayStop()
    {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_STOP, 0));
    }

    @Override
    public void onPosition(int position)
    {
        lastPostion = position;
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_POSITION,
                position));
    }

    @Override
    public void onVideoSize(int i, int i1, int i2)
    {

    }

    @Override
    public void onSeek(int position)
    {
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_SEEK, position));
    }

    @Override
    public void onAudioLevel(int i)
    {

    }

    @Override
    public void onCaching(final boolean b)
    {
       myHandler.post(new Runnable()
       {
           @Override
           public void run()
           {
               if(callback != null)
                   callback.isWait(b);
           }
       });
    }

    @Override
    public void onPlayPause()
    {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_PAUSE, 0));
    }

    @Override
    public void onPlayResume()
    {
        myHandler.sendMessage(myHandler.obtainMessage(MSG.MSG_ON_RESUME, 0));
    }


    @Override
    public void onPageSize(int position, int w, int h)
    {
        //文档翻页切换，开始显示
        myHandler.sendMessage(myHandler
                .obtainMessage(MSG.MSG_ON_PAGE, position));

    }

    @Override
    public void onVideoStart()
    {
        myHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                if(callback != null)
                    callback.onStart();
            }
        });
    }

    @Override
    public void onChat(List<ChatMsg> list)
    {

    }

    @Override
    public void onDocInfo(List<DocInfo> list)
    {

    }

    @Override
    public void onError(final int errorCode)
    {
        final String[] msg = new String[1];
        switch (errorCode)
        {
            case ERR_PAUSE:
                msg[0] = "暂停失败";
                break;
            case ERR_PLAY:
                msg[0] = "播放失败";
                break;
            case ERR_RESUME:
                msg[0] = "恢复失败";
                break;
            case ERR_SEEK:
                msg[0] = "进度变化失败";
                break;
            case ERR_STOP:
                msg[0] = "停止失败";
                break;
            default:
                msg[0] = "操作失败";
                break;
        }
        myHandler.post(new Runnable()
        {
            @Override
            public void run()
            {
                callback.onError(errorCode, msg[0]);
            }
        });
    }

    /**----------------------------------------------------------播放器回调--------------------------------------------------------------*/

    private boolean isTouch = false;
    private static final String DURATION = "DURATION";
    
    private int VIEDOPAUSEPALY = 0;

    private List<ChapterInfo> chapterList;

    private int lastPostion = 0;

    private String formateTime(int time)
    {
        return String.format(Locale.CHINA, "%02d", time / 3600) + ":"
                + String.format(Locale.CHINA, "%02d", time % 3600 / 60) + ":"
                + String.format(Locale.CHINA, "%02d", time % 3600 % 60);
    }

    private int videoAllDuration, videoNowDuration;
    
    Handler myHandler = new Handler(new Handler.Callback()
    {
        @Override
        public boolean handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MSG.MSG_ON_INIT:

                    int max = msg.getData().getInt(DURATION);
                    progress.setMax(max);
                    max = max / 1000;
                    videoAllDuration = max;
                    leftTime.setText(formateTime(videoAllDuration));
                    mVodPlayer.seekTo(lastPostion);
                    pauseResume.setImageResource(R.drawable.pause);
                    if(!TextUtils.isEmpty(vodId) && TextUtils.isEmpty(localpath))
                    {
                        String localPath = preferences.getString(vodId, "");
                        if(TextUtils.isEmpty(localPath))
                        {
                            download.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
                case MSG.MSG_ON_STOP:
                    progress.setMax(0);
                    VIEDOPAUSEPALY = 2;
                    download.setVisibility(View.GONE);
                    leftTime.setText(formateTime(videoAllDuration));
                    pauseResume.setImageResource(R.drawable.play);
                    break;
                case MSG.MSG_ON_VIDEOSIZE:

                    break;
                case MSG.MSG_ON_PAGE:

                    break;
                case MSG.MSG_ON_PAUSE:
                    VIEDOPAUSEPALY = 1;
                    pauseResume.setImageResource(R.drawable.play);
                    break;
                case MSG.MSG_ON_RESUME:
                    VIEDOPAUSEPALY = 0;
                    pauseResume.setImageResource(R.drawable.pause);
                    break;
                case MSG.MSG_ON_POSITION:
                    if (isTouch)
                    {
                        return false;
                    }else
                    {
                        int anyPosition = (Integer) msg.obj;
                        progress.setProgress(anyPosition);
                        anyPosition = anyPosition / 1000;
                        leftTime.setText(formateTime(videoAllDuration - anyPosition));
                    }
                    break;
                case MSG.MSG_ON_SEEK:
                    isTouch = false;
                    int anyPosition = (Integer) msg.obj;
                    progress.setProgress(anyPosition);
                    anyPosition = anyPosition / 1000;
                    leftTime.setText(formateTime(videoAllDuration - anyPosition));
                    break;
                case MSG.MSG_ON_AUDIOLEVEL:

                    break;
                default:
                    break;
            }
            return true;
        }
    });

    /**----------------------------------------------------------滑动进度--------------------------------------------------------------*/
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b){}

    @Override
    public void onStartTrackingTouch(SeekBar seekBar)
    {
        isTouch = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar)
    {
        if (null != mVodPlayer)
        {
            isTouch = false;
            int pos = seekBar.getProgress();
            mVodPlayer.seekTo(pos);
        }
    }
    /**----------------------------------------------------------滑动进度--------------------------------------------------------------*/

    public void handleScreenOritention()
    {
        if (ScreenUtils.isPortrait(mContext))
        {
            fullScreen.setImageResource(R.drawable.full_screen);
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            p.width = parentPortraitWidth;
            p.height = parentPortraitHeight;
            parent.setLayoutParams(p);
        } else
        {
            fullScreen.setImageResource(R.drawable.normal_screen);
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) parent.getLayoutParams();
            p.width = ScreenUtils.screenWidth(mContext);
            p.height = ScreenUtils.screenHeight(mContext);
            parent.setLayoutParams(p);
        }
    }

    public interface FullScreenClickListener
    {
        void vodClick();
    }

    public void setFullScreenClickListener(FullScreenClickListener cc)
    {
        ll = cc;
    }

    FullScreenClickListener ll;
}
